package com.mnb.base.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mnb.base.entity.SysUser;
import com.mnb.base.service.SysUserService;
import com.mnb.base.service.impl.SysPermissionService;
import com.mnb.base.utils.JwtUtils;
import com.mnb.common.utils.R;
import com.mnb.common.utils.RSAUtils;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


@RestController
public class LoginController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private HttpSession session;

    @RequestMapping("/login")
    public R login(SysUser loginUser, HttpSession session) {
        String password = loginUser.getPassword();
        String token;
        boolean flag = validateCaptcha(session, loginUser.getUserName(), loginUser.getCode(), loginUser.getUuid());
        if (!flag) {
            return R.fail("验证码错误");
        }
        SysUser user = sysUserService.selectByUserName(loginUser.getUserName());
        if(user == null){
            return R.fail("用户不存在");
        }
        if (password.equals(RSAUtils.decrypt(user.getPassword()))) {
            SysUser jwtUser = JwtUtils.setExpireTime(user);
            Map<String, Object> userInfoMap = new HashMap<String, Object>();
            userInfoMap.put("id", jwtUser.getUserId());
            userInfoMap.put("username", jwtUser.getUserName());
            userInfoMap.put("nickName", jwtUser.getNickName());
            //使用工具类生成token
            token = JwtUtils.createJwtToken(userInfoMap);
            jwtUser.setToken(token);
            session.setAttribute("user", jwtUser);
            return R.ok(jwtUser);
        } else {
            return R.fail("用户名密码错误");
        }
    }

    @RequestMapping("/dddd")
    public String test() {
        return "dddd";
    }

    /**
     * 校验验证码
     *
     * @param session  会话
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public boolean validateCaptcha(HttpSession session, String username, String code, String uuid) {
        String captcha = CaptchaController.getCaptcha(session, uuid);
        return code.equalsIgnoreCase(captcha);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getUserInfo")
    public R getUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = getUserId().toString();
        SysUser user = sysUserService.selectByUserId(userId);
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return R.ok(ajax);

    }


    public Object getUserId()
    {
        SysUser user = (SysUser) session.getAttribute("user");
        if(user == null){
            throw new RuntimeException("用户未登录");
        }
        return user.getUserId();
    }
}
